package com.example.waterdispenserm2.mo.usbmain;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;
import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityUsbMainInductionCookerBinding;
import com.example.waterdispenserm2.util.MyLog;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class UsbMainInductionCookerActivity extends BasicsActivity<ActivityUsbMainInductionCookerBinding>  implements UsbMainInductionCookerController.ControllerCallback{

    private UsbMainInductionCookerController controller;
    private ImageView[] leds = new ImageView[8];
    private int thousands = 0, hundreds = 0, tens = 0, units = 0;
    private byte ledStatus = 0;
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
// 初始化控制器
        controller = new UsbMainInductionCookerController(this, this);


        binding.ivMessage.setOnClickListener(v->{finish();});


        binding.connectBtn.setOnClickListener(v -> {
            if (controller.connectToDevice()) {
                updateStatus("正在连接设备...");
            } else {
                updateStatus("连接失败");
            }
        });
        binding.disconnectBtn.setOnClickListener(v -> {
            controller.disconnect();
            updateStatus("已断开连接");
        });

        // 数字控制按钮
        setupDigitControls();

        // LED控制按钮
        setupLedControls();

        // 初始显示
        updateDisplay();
        updateStatus("准备就绪");
    }

    @Override
    protected ActivityUsbMainInductionCookerBinding getViewBinding() {
        return ActivityUsbMainInductionCookerBinding.inflate(LayoutInflater.from(this));
    }


    private void setupDigitControls() {
        // 千位控制
        findViewById(R.id.thousands_up).setOnClickListener(v -> {
            thousands = (thousands + 1) % 10;
            updateDisplay();
        });
        findViewById(R.id.thousands_down).setOnClickListener(v -> {
            thousands = (thousands + 9) % 10;
            updateDisplay();
        });

        // 百位控制
        findViewById(R.id.hundreds_up).setOnClickListener(v -> {
            hundreds = (hundreds + 1) % 10;
            updateDisplay();
        });
        findViewById(R.id.hundreds_down).setOnClickListener(v -> {
            hundreds = (hundreds + 9) % 10;
            updateDisplay();
        });

        // 十位控制
        findViewById(R.id.tens_up).setOnClickListener(v -> {
            tens = (tens + 1) % 10;
            updateDisplay();
        });
        findViewById(R.id.tens_down).setOnClickListener(v -> {
            tens = (tens + 9) % 10;
            updateDisplay();
        });

        // 个位控制
        findViewById(R.id.units_up).setOnClickListener(v -> {
            units = (units + 1) % 10;
            updateDisplay();
        });
        findViewById(R.id.units_down).setOnClickListener(v -> {
            units = (units + 9) % 10;
            updateDisplay();
        });
    }

    private void setupLedControls() {
        int[] ledButtons = {
                R.id.toggle_frying, R.id.toggle_porridge, R.id.toggle_hotpot,
                R.id.toggle_high_fire, R.id.toggle_low_fire, R.id.toggle_boil_water,
                R.id.toggle_steam, R.id.toggle_stew
        };

        byte[] ledMasks = {
                UsbMainInductionCookerController.LED_FRYING,
                UsbMainInductionCookerController.LED_PORRIDGE,
                UsbMainInductionCookerController.LED_HOTPOT,
                UsbMainInductionCookerController.LED_HIGH_FIRE,
                UsbMainInductionCookerController.LED_LOW_FIRE,
                UsbMainInductionCookerController.LED_BOIL_WATER,
                UsbMainInductionCookerController.LED_STEAM,
                UsbMainInductionCookerController.LED_STEW
        };

        for (int i = 0; i < ledButtons.length; i++) {
            int index = i;
            findViewById(ledButtons[i]).setOnClickListener(v -> {
                ledStatus ^= ledMasks[index]; // 切换LED状态
                updateLedDisplay();
            });
        }
    }

    private void updateDisplay() {
        // 更新数码管显示
        String displayText = String.format(Locale.getDefault(),
                "%d%d%d%d", thousands, hundreds, tens, units);
        binding.displayValue.setText(displayText);

        // 更新LED显示
        updateLedDisplay();

        // 更新控制器数据
        controller.setDisplayData(thousands, hundreds, tens, units, ledStatus);
    }

    private void updateLedDisplay() {

        if (leds[0] == null) return;

        // 根据LED状态更新指示灯
        int ledOnColor = ContextCompat.getColor(this, R.color.led_on);
        int ledOffColor = ContextCompat.getColor(this, R.color.led_off);

        leds[0].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_FRYING) != 0 ? ledOnColor : ledOffColor);
        leds[1].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_PORRIDGE) != 0 ? ledOnColor : ledOffColor);
        leds[2].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_HOTPOT) != 0 ? ledOnColor : ledOffColor);
        leds[3].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_HIGH_FIRE) != 0 ? ledOnColor : ledOffColor);
        leds[4].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_LOW_FIRE) != 0 ? ledOnColor : ledOffColor);
        leds[5].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_BOIL_WATER) != 0 ? ledOnColor : ledOffColor);
        leds[6].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_STEAM) != 0 ? ledOnColor : ledOffColor);
        leds[7].setColorFilter((ledStatus & UsbMainInductionCookerController.LED_STEW) != 0 ? ledOnColor : ledOffColor);
    }

    private void updateStatus(String message) {
        binding.connectionStatus.setText(message);
    }

    private void appendToMonitor(String message) {
        MyLog.d("--接收---",message);
        String time = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(new Date());
        String currentText = binding.dataMonitor.getText().toString();
        String newText = "[" + time + "] " + message + "\n" + currentText;

        // 限制显示行数
        if (newText.split("\n").length > 20) {
            newText = newText.substring(0, newText.lastIndexOf("\n", newText.lastIndexOf("\n") - 1));
        }

        binding.dataMonitor.setText(newText);
    }

    @Override
    public void onConnectionStatusChanged(boolean connected) {
        runOnUiThread(() -> {
            if (connected) {
                binding.connectionStatus.setText("已连接设备");
                binding.connectionStatus.setTextColor(Color.GREEN);
            } else {
                binding.connectionStatus.setText("未连接");
                binding.connectionStatus.setTextColor(Color.RED);
            }
        });
    }

    @Override
    public void onError(String errorMessage) {
        runOnUiThread(() -> {
            binding.connectionStatus.setText("错误: " + errorMessage);
            binding.connectionStatus.setTextColor(Color.RED);
            appendToMonitor("错误: " + errorMessage);
        });
    }

    @Override
    public void onKeyReceived(int keyCode) {
        runOnUiThread(() -> {
            binding.lastKeyReceived.setText("接收按键: " + UsbMainInductionCookerController.getKeyName(keyCode));
            appendToMonitor("接收按键: " + UsbMainInductionCookerController.getKeyName(keyCode));
        });
    }

    @Override
    public void onDataReceived(byte[] data) {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder();
            sb.append("接收数据: ");
            for (byte b : data) {
                sb.append(String.format("0x%02X ", b));
            }
            appendToMonitor(sb.toString());
        });
    }

    @Override
    public void onDataSent(byte[] data) {
        runOnUiThread(() -> {
            StringBuilder sb = new StringBuilder();
            sb.append("发送数据: ");
            for (byte b : data) {
                sb.append(String.format("0x%02X ", b));
            }
            appendToMonitor(sb.toString());
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (controller != null) {
            controller.disconnect();
        }
    }
}